package cn.edu.lingnan.controllerV1;

import cn.edu.lingnan.context.BaseContext;
import cn.edu.lingnan.service.StatisticsService;
import cn.edu.lingnan.user.Statistics.ExamAllStatsVO;
import cn.edu.lingnan.user.dtos.Result;
import cn.edu.lingnan.user.dtos.UserStatisticsRequestDTO;
import cn.edu.lingnan.user.pojos.ExamedPaper;
import cn.edu.lingnan.user.pojos.UserExam;
import cn.edu.lingnan.user.vos.PaperSatisticsVo;
import cn.edu.lingnan.utils.AIChatUtils;
import cn.edu.lingnan.user.vos.*;
import cn.edu.lingnan.utils.OpenAIChatStreaming;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/statistics")
@Slf4j
public class StatisticsController {

    @Autowired
    private StatisticsService statisticsService;

    //查询考后试卷统计
    @GetMapping("/examedPaper")
    public Result<?> examedPaper(@RequestParam("paperId") Integer paperId,
                                 @RequestParam("examId")Integer examId,
                                 @RequestParam( value = "userId" , required = false ) Integer userId) throws IOException {
        log.info("查询考后试卷统计");
        ExamedPaper examedPaper = statisticsService.getExamedPaper(paperId,examId,userId);
        if(examedPaper == null){
            return  Result.notapproved("未批阅");
        }
        return Result.success(examedPaper);
    }



    //统计考试数据
    @GetMapping("/statistics_Score")
    public Result<?> statisticsScore(@RequestParam("examId") Integer examId, @RequestParam("paperId") Integer paperId) {
        log.info("统计考试数据");
        PaperSatisticsVo paperSatisticsVo = statisticsService.statisticsScore(examId, paperId);
        if(paperSatisticsVo == null){
            return Result.notapproved("未批阅");
        }
        return Result.success( paperSatisticsVo );
    }

    /**
     * 一次性返回 (a)(b)(c)(d) 统计结果
     */
    @GetMapping("/exam/all")
    public Result<?> getAllExamStats(@RequestParam("examId") Integer examId) {
        ExamAllStatsVO vo =statisticsService.getAllExamStats(examId);
        return Result.success(vo);
    }

    //批阅
    @PostMapping("/ReviewExamedPaper")
    public Result<?> ReviewExamedPaper(@RequestBody UserExam userExam) {
        statisticsService.ReviewExamedPaper(userExam);
        return Result.success();
    }

    /**
     * POST请求：获取用户统计数据。
     *
     * @param requestDTO 统计请求参数，包括日期和周期。
     * @return 用户统计视图对象 VO。
     */
    @PostMapping("/getStatistics")
    public Result<?> getUserStatistics(@RequestBody UserStatisticsRequestDTO requestDTO) {
        return  Result.success(statisticsService.getUserStatistics(requestDTO));
    }


    @Autowired
    private AIChatUtils aiChatUtils;

    // 获取诊断报告
    @GetMapping("/getDiagnosis")
    public Result<?> getDiagnosis(@RequestParam("paperId") Integer paperId,
                                  @RequestParam("examId") Integer examId,
                                  @RequestParam(value = "userId", required = false) Integer userId) throws IOException, ExecutionException, InterruptedException {

            log.info("查询考智能诊断报告 ");
            ExamedPaper examedPaper = statisticsService.getExamedPaper(paperId, examId, userId);


        if(examedPaper.getDiagnosis() == null || examedPaper.getDiagnosis().isEmpty()){
                String  prompt = createPrompt(examedPaper);
                log.info("prompt:{}",prompt);
//               String result = aiChatUtils.processChat(prompt);
            String result= OpenAIChatStreaming.chatStream(prompt);
                //存储诊断报告
                statisticsService.saveDiagnosis(examId, BaseContext.getCurrentId(), result);
                examedPaper.setDiagnosis(result);
                return Result.success(result);
            }
            return Result.success(examedPaper.getDiagnosis());

        }

    private String createPrompt(ExamedPaper examedPaper) {
        PaperWithQuestionVo paperWithQuestionVo = examedPaper.getPaperWithQuestionVo();
        StringBuilder prompt = new StringBuilder();
        prompt.append("请根据以下试卷信息，生成一份智能诊断报告(包括智能分析和学习建议)：\n");
        //试卷信息
        prompt.append("试卷信息");
        prompt.append("试卷名称：").append(paperWithQuestionVo.getPaperName()).append("\n");
        prompt.append("单选题总分：").append(paperWithQuestionVo.getSingleChoiceScore()).append("\n");
        prompt.append("多选题总分：").append(paperWithQuestionVo.getMultipleChoiceScore()).append("\n");
        prompt.append("判断题总分：").append(paperWithQuestionVo.getTrialScore()).append("\n");
        prompt.append("填空题总分：").append(paperWithQuestionVo.getFillScore()).append("\n");
        prompt.append("简答题总分：").append(paperWithQuestionVo.getExpoundScore()).append("\n");

        List<QuestionVO> questions = paperWithQuestionVo.getQuestions();
         prompt.append("试卷试题：\n");
         for (QuestionVO question : questions) {
             prompt.append("问题编号：").append(question.getQuestionId()).append("\n");
             prompt.append("问题：").append(question.getQuestionName()).append("\n");
             prompt.append("类型：").append(getQuestionType(question.getQuestionType())).append("\n");
             prompt.append("正确答案：").append(question.getCorrectAnswer()).append("\n");
             prompt.append("分值：").append(question.getQuestionScore()).append("\n");

         }

         //我的得分
         prompt.append("我的总得分：").append(examedPaper.getTotalScore()).append("\n");
         prompt.append("我的得分详情：\n");
         prompt.append("单选题得分：").append(examedPaper.getSingleChoiceScore()).append("\n");
         prompt.append("多选题得分：").append(examedPaper.getMultipleChoiceScore()).append("\n");
         prompt.append("判断题得分：").append(examedPaper.getTrialScore()).append("\n");
         prompt.append("填空题得分：").append(examedPaper.getFillScore()).append("\n");
         prompt.append("简答题得分：").append(examedPaper.getExpoundScore()).append("\n");
         //我的答案
         prompt.append("我的答案：\n").append(examedPaper.getAnswers()).append("\n");



     return  prompt.toString();
    }

    //定义一个题目类型映射方法
    private String getQuestionType(Integer questionType) {
        switch (questionType) {
            case 1:
                return "单选题";
            case 2:
                return "多选题";
            case 3:
                return "判断题";
            case 4:
                return "填空题";
            case 5:
                return "简答题";
            default:
                return "未知类型";
        }
    }



    //下面是管理员统计的controller
    // 统计平均分排名前三的学生
    @GetMapping("/top-students")
    public Result<List<TopStudentVO>> getTopStudents() {
        List<TopStudentVO> topStudents = statisticsService.getTopStudents();
        return Result.success(topStudents);
    }

    // 统计所有学生的分数段人数
    @GetMapping("/score-ranges")
    public Result<List<ScoreRangeVO>> getScoreRanges() {
        List<ScoreRangeVO> scoreRanges = statisticsService.getScoreRanges();
        return Result.success(scoreRanges);
    }

    // 统计成绩最好的三份试卷
    @GetMapping("/best-exams")
    public Result<List<ExamPerformanceVO>> getBestExams() {
        List<ExamPerformanceVO> bestExams = statisticsService.getBestExams();
        return Result.success(bestExams);
    }

    // 统计成绩最差的三份试卷
    @GetMapping("/worst-exams")
    public Result<List<ExamPerformanceVO>> getWorstExams() {
        List<ExamPerformanceVO> worstExams = statisticsService.getWorstExams();
        return Result.success(worstExams);
    }

    // 统计最近一年考试的平均分变化趋势
    @GetMapping("/average-score-trend")
    public Result<List<AverageScoreTrendVO>> getAverageScoreTrend() {
        List<AverageScoreTrendVO> averageScoreTrend = statisticsService.getAverageScoreTrend();
        return Result.success(averageScoreTrend);
    }
}
